package jrandom.wizards;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.*;
import jrandom.JRandomPlugin;
import jrandom.model.TestCase;


public class NewJRandomTestCaseWizard extends Wizard implements INewWizard {
	
	private IWorkbench workbench;
	private IStructuredSelection selection;
	
	private JRandomTestCaseWizardPage1 page1;
	private JRandomTestCaseWizardPage2 page2;
	private JRandomTestCaseWizardPage3 page3;

	/**
	 * Constructor for NewJRandomTestCaseWizard.
	 */
	public NewJRandomTestCaseWizard() {
		super();
		setWindowTitle("New JRandom Case");
		setNeedsProgressMonitor(true);
		setDefaultPageImageDescriptor(JRandomPlugin.getImageDescriptor("icons/newtest_wiz.png"));
	}
	
	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		super.addPages();
		page1 = new JRandomTestCaseWizardPage1(selection);
		addPage(page1);
		page2 = new JRandomTestCaseWizardPage2(page1);
		addPage(page2);
		page3 = new JRandomTestCaseWizardPage3(page2);
		addPage(page3);
		
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		TestCase testCase = new TestCase(this, page3.getMethod(), page3.getMinValues(), 
											page3.getMaxValues(), page2.getTestCaseNumber());
		
		testCase.setOutputFile(page1.getFileName(), page1.isXMLSelected());
		testCase.setARTorRT(page2.isARTSelected());

		try {
			getContainer().run(true, false, testCase);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.workbench = workbench;
		this.selection = selection;
	}
	
	public IStructuredSelection getSelection() {
		return selection;
	}

	public IWorkbench getWorkbench() {
		return workbench;
	}
	
}